﻿using UnityEngine;
using System.Collections;

public class PlatformScript : MonoBehaviour
{
    public SpriteRenderer[] spriteRenderers;
    public GameObject obstacle = null;
    private bool isStartTimer;
    private float fallTime;
    private Rigidbody2D myBody;

    public void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
    }

    public void Init(Sprite sprite, float fallTime)
    {
        myBody.bodyType = RigidbodyType2D.Static;
        isStartTimer = true;
        this.fallTime = fallTime;
        for (int i = 0; i < spriteRenderers.Length; i++)
        {
            spriteRenderers[i].sprite = sprite;
        }


        if (obstacle != null)
        {
            if (Random.Range(0,2) == 0)
            {
                //Debug.Log($"Right Obstacle. {obstacle.transform.localPosition.x}");
                obstacle.transform.localPosition = new Vector3(-obstacle.transform.localPosition.x,
                    obstacle.transform.localPosition.y, obstacle.transform.localPosition.z);
            }
        }
    }

    private void Update()
    {
        if (!GameManager.Instance.IsGameStarted || GameManager.Instance.IsGameOver || GameManager.Instance.IsPause || !GameManager.Instance.IsPlayerMove)
        {
            return;
        }

        if (isStartTimer)
        {
            fallTime -= Time.deltaTime;
            if (fallTime < 0)
            {
                isStartTimer = false;
                if (myBody.bodyType != RigidbodyType2D.Dynamic)
                {
                    myBody.bodyType = RigidbodyType2D.Dynamic;
                    StartCoroutine(DelayHide());
                }
            }
        }

        if (transform.position.y - Camera.main.transform.position.y < -6)
        {
            gameObject.SetActive(false);
        }
    }

    private IEnumerator DelayHide()
    {
        yield return new WaitForSeconds(1f);
        gameObject.SetActive(false);
    }

}
